package com.atjg.autocat.main

import android.annotation.SuppressLint
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.atjg.autocat.R
import com.atjg.autocat.bean.GoodBean
import com.atjg.autocat.bean.MqMsgBean
import com.atjg.autocat.bean.ProgressBean
import com.atjg.autocat.databinding.ActivityMainBinding
import com.atjg.autocat.dialog.GoodDialog
import com.atjg.autocat.dialog.QRCodeDialog
import com.atjg.autocat.dialog.SuccessDialog
import com.atjg.autocat.mqtt.IGetMessageCallBack
import com.atjg.autocat.mqtt.MQTTService
import com.atjg.autocat.mqtt.MqttManager.printinfo
import com.atjg.autocat.mqtt.MyServiceConnection
import com.atjg.autocat.receiver.NetworkChangeReceiver
import com.atjg.autocat.serialPort.PortUtils
import com.atjg.autocat.serialPort.PortUtils.Companion.crc16
import com.atjg.autocat.serialPort.PortUtils.Companion.crc16CCITT
import com.atjg.autocat.utils.Bitmap2FileUtils
import com.atjg.autocat.utils.CameraUtils
import com.atjg.autocat.utils.DeviceUtils
import com.atjg.autocat.utils.FileUtils
import com.atjg.autocat.utils.MusicPlayUtils
import com.atjg.autocat.viewModel.MainViewModel
import com.azhon.appupdate.config.UpdateConfiguration
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.zhy.baselibrary.adapter.BaseAdapterHelper
import com.zhy.baselibrary.adapter.recycler.RecyclerAdapter
import com.zhy.baselibrary.base.BaseActivity
import com.zhy.baselibrary.expand.ToastMgr
import com.zhy.baselibrary.shape.RoundTextView
import com.zhy.baselibrary.utils.AppManager
import com.zhy.baselibrary.utils.Klog
import com.zhy.baselibrary.utils.click
import com.zhy.baselibrary.utils.clickWithTrigger
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale


class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {
    private val shopPort = "/dev/ttyS0"
    private val cleanPort = "/dev/ttyS1"
    private var clickCount = 0
    private var adapter: RecyclerAdapter<GoodBean>? = null
    private val waitTime: Long = 2000
    private var touchTime: Long = 0
    private var successDialog: SuccessDialog? = null
    private var tabList = ArrayList<String>()
    private var goodsList = ArrayList<GoodBean>()
    private var adapterTitle: RecyclerAdapter<String>? = null
    private var selectTabIndex = 0
    private var goodCount = 1
    private var sumJiFen = 0f
    private var orderNo = ""
    private var goodId = ""
    private var screenWidth = ScreenUtils.getScreenWidth()
    private var startPayTime = 0L
    private var goodDialog: GoodDialog? = null
    private var goodsItem: GoodBean? = null
    private var taocan = "tc1"
    private var queryStatus = false
    private var cameraUtils: CameraUtils? = null
    private var progress = -1
    private var endTime = 0L
    private var stopTime = 0L
    private var stopProgress = ""
    private var progressList = arrayListOf<ProgressBean>(
        ProgressBean("清洗",0,1),
        ProgressBean("沐浴露",0,2),
        ProgressBean("清洗",0,3),
        ProgressBean("护毛素",0,4),
        ProgressBean("清洗",0,5),
        ProgressBean("烘干",0,6),
        ProgressBean("消毒",0,7)
    )
    private val myServiceConnection by lazy {
        MyServiceConnection()
    }
    private val portUtils by lazy {
        PortUtils.initSerial()
    }
    private val boxAdapter by lazy {
        object : RecyclerAdapter<GoodBean>(this, R.layout.adapter_type_main) {
            @SuppressLint("DefaultLocale", "NotifyDataSetChanged")
            override fun convert(helper: BaseAdapterHelper, item: GoodBean, position: Int) {
                val ivTitle = helper.getView<ImageView>(R.id.ivTitle)
                val layoutParams = ivTitle.layoutParams
                layoutParams.width = screenWidth / 5 * 2
                layoutParams.height = 232
                when(position){
                    0->{
                        if(item.imageUrl.isNotEmpty()){
                            Glide.with(this@MainActivity).load(item.imageUrl)
                                .skipMemoryCache(false)
                                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                                .into(ivTitle)
                        }else{
                            ivTitle.setImageResource(R.mipmap.taocan_a)
                        }
                    }
                    1->{
                        if(item.imageUrl.isNotEmpty()){
                            Glide.with(this@MainActivity).load(item.imageUrl)
                                .skipMemoryCache(false)
                                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                                .into(ivTitle)
                        }else{
                            ivTitle.setImageResource(R.mipmap.taocan_b)
                        }
                    }
                    2->{
                        if(item.imageUrl.isNotEmpty()){
                            Glide.with(this@MainActivity).load(item.imageUrl)
                                .skipMemoryCache(false)
                                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                                .into(ivTitle)
                        }else{
                            ivTitle.setImageResource(R.mipmap.taocan_c)
                        }
                    }
                }
                helper.setText(R.id.tvComboName,item.comboName)
                    .setText(R.id.tvCareTime,"洗护：${item.careTime}分钟")
                    .setText(R.id.tvDryTime,"烘干：${item.dryTime}分钟")
                    .setText(R.id.tvPrice,"价格：￥${item.price}元")
                helper.view.clickWithTrigger {

                 val qrcode = when(item.columnPosition){
                       "1"->{
                           taocan = "tc1"
                           "qrcode_1"
                       }
                     "2"->{
                         taocan = "tc2"
                         "qrcode_2"
                     }
                     else->{
                         taocan = "tc3"
                         "qrcode_3"
                     }
                   }
                    if (queryStatus){
                        ToastMgr.show("请稍后，正在检测水位...")
                        return@clickWithTrigger
                    }
                    myServiceConnection.mqttService.publishMsg(qrcode)
                }
            }
        }
    }
    private val progressAdapter by lazy {
        object : RecyclerAdapter<ProgressBean>(this, R.layout.adapter_progress,progressList) {
            @SuppressLint("DefaultLocale", "NotifyDataSetChanged")
            override fun convert(helper: BaseAdapterHelper, item: ProgressBean, position: Int) {
                val tvTitle = helper.getView<TextView>(R.id.tvTitle)
                tvTitle.text = item.title
                val tvFlag = helper.getView<RoundTextView>(R.id.tvFlag)
                if(progress == position){
                    tvTitle.setTextColor(Color.parseColor("#F8BCBB"))
                    tvFlag.delegate.backgroundColor = Color.parseColor("#F8BCBB")
                }else{
                    tvTitle.setTextColor(Color.parseColor("#000000"))
                    tvFlag.delegate.backgroundColor = Color.parseColor("#999999")
                }
            }
        }
    }
    private val networkChangeReceiver by lazy {
        NetworkChangeReceiver(object : NetworkChangeReceiver.OnNetworkChangeListener {
            override fun onNetworkConnected() {
                model.goodsList(DeviceUtils.getDeviceId())
                model.queryBanner()
                model.queryCombo(DeviceUtils.getDeviceId())
                initMqtt()
            }

            override fun onNetworkDisconnected() {

            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    override fun initialize() {
        binding.tvProductName.text = App.projectName
        binding.tvVersion.text = "版本号：${AppUtils.getAppVersionName()}.${AppUtils.getAppVersionCode()}"
        ActivityUtils.finishActivity(SplashActivity::class.java)
        initTypeAdapter()
        initRecyclerView()
        initProgress()
        val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(networkChangeReceiver, filter)
        val layoutParams = binding.ivShop.layoutParams
        layoutParams.height = 256
        initBanner()
        initSerial()
    }
    private fun initProgress(){
        binding.rvProgress.layoutManager = GridLayoutManager(this, 7)
        binding.rvProgress.adapter = progressAdapter
    }
    private fun initBanner(){
        val layoutParams = binding.flBanner.layoutParams
        val width = screenWidth / 5 * 2
        layoutParams.width = width
        layoutParams.height = 350

        val mList = ArrayList<Int>()
        mList.add(R.mipmap.icon_banner1)
        mList.add(R.mipmap.icon_banner2)
        mList.add(R.mipmap.icon_banner3)
        binding.flBanner.setImages(mList,0)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initTypeAdapter() {
        val layoutManager = binding.llTaoCan.layoutParams
        layoutManager.width = ScreenUtils.getScreenWidth() / 5 * 2
        binding.rvTaoCan.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rvTaoCan.adapter = boxAdapter
    }
    private fun initRecyclerView() {
        binding.recycler.layoutManager = GridLayoutManager(
            this, 4, RecyclerView.VERTICAL, false
        )
        adapter = object : RecyclerAdapter<GoodBean>(this, R.layout.item_shop) {
            @SuppressLint("DefaultLocale")
            override fun convert(helper: BaseAdapterHelper, item: GoodBean, position: Int) {
                val width = (ScreenUtils.getScreenWidth() / 5 * 3 / 4) - SizeUtils.dp2px(10f)
                val height=  216 * width / 288
                val ivShop = helper.getView<ImageView>(R.id.ivGood)
                val shopLayout = ivShop.layoutParams
                shopLayout.height =height
                shopLayout.width = width
                Glide.with(this@MainActivity).load(item.photoUrl)
                    .skipMemoryCache(false)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .into(ivShop)
                helper.setVisibleOrGone(R.id.tvSoldOut, item.currentGoodsSum <= 0)
                    .setText(
                        R.id.tvJiFen,
                        if (item.currentJifen > 0) {
                            String.format("%.2f", item.currentJifen)
                        } else {
                            String.format("%.2f", item.jifen)
                        }
                    )
                    .setText(R.id.tvDoorNum, "#${item.doorNum}")
            }
        }
        binding.recycler.adapter = adapter
        adapter?.setOnClickItemListener { item, position ->
            if (item.currentGoodsSum <= 0) {
                ToastMgr.show("该商品已售罄")
                return@setOnClickItemListener
            }
            goodId = item.id
            goodsItem = item
            showGood(item)
        }
    }
    private fun showGood(item: GoodBean) {
        goodDialog = GoodDialog(this, item, object : GoodDialog.OnGoodSumListener {
            override fun onClick(item: GoodBean, count: Int, sumNum: String) {
                goodCount = count
                sumJiFen = sumNum.toFloat()
            }


            override fun onQR(item: GoodBean, count: Int, sumNum: String) {
                goodCount = count
                goodDialog?.dismiss()
                model.queryNativePay(item.id)
            }
        })
        XPopup.Builder(this)
            .dismissOnBackPressed(true)
            .dismissOnTouchOutside(true)
            .asCustom(goodDialog)
            .show()
    }
    override fun setListener() {
        super.setListener()
        binding.ivShop.click {
            clickCount++
            if(clickCount == 5){
                clickCount = 0
                ActivityUtils.startActivity(ConfigActivity::class.java)
            }
        }
    }

   private fun initMqtt() {
        myServiceConnection.setIGetMessageCallBack(object : IGetMessageCallBack {
            override fun setMessage(str: String?, mqttMessage: MqttMessage?) {
                runOnUiThread {
                    val mqMsg = mqttMessage.toString()
                    val mqMsgBean = Gson().fromJson(mqMsg, MqMsgBean::class.java)
                    if (!mqMsgBean.price.isNullOrEmpty()){
                        val qrDialog = QRCodeDialog(this@MainActivity,mqMsgBean.qrcodeStr,mqMsgBean.price)
                        XPopup.Builder(this@MainActivity)
                            .autoFocusEditText(false)
                            .asCustom(qrDialog)
                            .show()
                    }else{
                        if (!mqMsgBean.Msg.isNullOrEmpty()){
                            when (mqMsgBean.Msg) {
                                "run_1" -> {
                                    orderNo = mqMsgBean.orderNo?:"test01010101"
                                    taocan = "tc1"
                                    execute()
                                }
                                "run_2" -> {
                                    orderNo = mqMsgBean.orderNo?:"test01010101"
                                    taocan = "tc2"
                                    execute()
                                }
                                "run_3" -> {
                                    orderNo = mqMsgBean.orderNo?:"test01010101"
                                    taocan = "tc3"
                                    execute()
                                }
                            }
                        }
                    }
                }
            }

            override fun setStatus(str: String, error: String) {
                runOnUiThread {
                    ToastMgr.show(str + error)
                }
            }
        })
        val intent = Intent(
            this,
            MQTTService::class.java as Class<*>
        )
        bindService(intent, myServiceConnection, 1)
    }

 @OptIn(ExperimentalStdlibApi::class)
 @SuppressLint("SimpleDateFormat", "SetTextI18n")
 private fun execute(){
     val time1 =  SPUtils.getInstance(taocan).getInt("time1")
     val time2 =  SPUtils.getInstance(taocan).getInt("time2")
     val time3 =  SPUtils.getInstance(taocan).getInt("time3")
     val time4 =  SPUtils.getInstance(taocan).getInt("time4")
     val time5 =  SPUtils.getInstance(taocan).getInt("time5")
     val time6 =  SPUtils.getInstance(taocan).getInt("time6")
     val sumTime = time1 + time2 + time3 + time4 + time5 + time6
     endTime = System.currentTimeMillis() + sumTime * 1000
     val endDate =  SimpleDateFormat("HH:mm").format(endTime)
     binding.tvTimeEnd.text = "预计结束时间：$endDate"
     //第一步 开门 0f 06 00 16 00 01
     val array = byteArrayOf(0x0f,0x06,0x00,0x16,0x00,0x01).crc16().toHexString()
     portUtils.sendHex(cleanPort,array,"fun-open")
 }

    @OptIn(ExperimentalStdlibApi::class)
    @SuppressLint("SetTextI18n", "SimpleDateFormat", "DefaultLocale", "NotifyDataSetChanged",
        "SuspiciousIndentation"
    )
    override fun setData() {
        super.setData()
        model.queryCombo.observe(this,{
            if (!it.isNullOrEmpty()){
                boxAdapter.clear()
                boxAdapter.addAll(it)
            }
        })
        model.queryBitmap.observe(this,{
            if(it!=null){
                val filePath = Bitmap2FileUtils.saveBitmapFile(
                    it, "${externalCacheDir}/netImage.jpg"
                )
                model.uploadImg(orderNo,File(filePath))
                App.mHanler?.postDelayed({
                    usbTakPhoto()
                },10000)
            }else{
                usbTakPhoto()
            }
        })
        model.uploadImg.observe(this,{
        })
        model.queryBanner.observe(this,{
            //1=广告轮播图，2=套餐一广告图，3=套餐二广告图，4=套餐三广告图，5=售货机海报；
            if (!it.isNullOrEmpty()){
              val bannerList = it.filter { item-> item.type == 1.0 }
                if (bannerList.isNotEmpty()){
                    binding.flBanner.setImagesUrl(bannerList.map { item->item.url},0)
                }
                val shop =   it.find { item-> item.type == 5.0 }
                if (shop !=null){
                    Glide.with(this).load(shop.url)
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                        .skipMemoryCache(false)
                        .into(binding.ivShop)
                }
            }
        })
        model.queryOrderStatus.observe(this,{
            if (it.payStatus == "1"){
                showSuccess()
                //支付完成  开始出货
                var hex16 = goodsItem!!.doorNum
                if (hex16.length == 1) {
                    hex16 = "0$hex16"
                }
                val msg = byteArrayOf(
                    0x55,
                    0xAA.toByte(),
                    0x04,
                    0x01,
                    0x06,
                    hex16.toByte(),
                    0x01
                ).crc16CCITT().toHexString()
                portUtils.sendHex(shopPort,msg,"shopOut")
            }else{
                //支付失败
                if (System.currentTimeMillis() - startPayTime <= 10 * 60 * 1000){
                    queryOrderState()
                }else{
                    MusicPlayUtils.playBgM(this,R.raw.music_pay_fail)
                }
            }
        })
        model.queryNativePay.observe(this,{
            orderNo = it.orderNo
            val qrDialog = QRCodeDialog(this,it.url)
            XPopup.Builder(this)
                    .autoFocusEditText(false)
                    .asCustom(qrDialog)
                    .show()
            App.mHanler?.postDelayed({
                startPayTime = System.currentTimeMillis()
                queryOrderState()
            },5000)

        })
        model.goodsList.observe(this, {
            if (!it.isNullOrEmpty()) {
                goodsList.clear()
                goodsList.addAll(it)
                goodsList.sortBy { item -> item.doorNum.toInt() }
                val tabListSize = (it.size / 10).toInt()
                if (tabListSize <= 6) {
                    val str =
                        arrayListOf("第一层", "第二层", "第三层", "第四层", "第五层", "第六层")
                    for (i in 0..<6) {
                        tabList.add(str[i])
                    }
                } else {
                    val str =
                        arrayListOf("第一层", "第二层", "第三层", "第四层", "第五层", "第六层")
                    for (i in 0..<6) {
                        tabList.add(str[i])
                    }
                }
                if (tabList.size == 0) {
                    return@observe
                }
                initTitleRecyclerView()
                val subList = goodsList.filter { item ->
                    item.doorNum.toInt() <= (selectTabIndex + 1) * 10 &&
                            item.doorNum.toInt() > (selectTabIndex) * 10
                }
                adapter?.clear()
                adapter?.addAll(subList)
            }
        })
        model.queryVersion.observe(this, {
            upDataVersion(it.apkurl, it.apkversion)
        })
    }
    private fun queryOrderState(){
        App.mHanler?.postDelayed({
            model.queryOrderStatus(orderNo)
        },5000)
    }
    @SuppressLint("NotifyDataSetChanged")
    private fun initTitleRecyclerView() {
        binding.recyclerTab.layoutManager = GridLayoutManager(
            this, 6, RecyclerView.VERTICAL, false
        )
        adapterTitle =
            object : RecyclerAdapter<String>(this, R.layout.item_shop_title) {
                @SuppressLint("DefaultLocale")
                override fun convert(helper: BaseAdapterHelper, item: String, position: Int) {
                    val tTitle = helper.getView<TextView>(R.id.tTitle)
                    tTitle.text = item
                    val llTitle = helper.getView<LinearLayout>(R.id.llTitle)
                    if (selectTabIndex == position) {
                        llTitle.setBackgroundColor(Color.parseColor("#2C94F8"))
                    } else {
                        llTitle.setBackgroundColor(Color.parseColor("#F8BCBB"))
                    }
                }
            }
        binding.recyclerTab.adapter = adapterTitle
        adapterTitle?.addAll(tabList)
        adapterTitle?.setOnClickItemListener { item, position ->
            selectTabIndex = position
            adapterTitle?.notifyDataSetChanged()
            val subList = goodsList.filter { goodItem ->
                goodItem.doorNum.toInt() <= (selectTabIndex + 1) * 10 &&
                        goodItem.doorNum.toInt() > (selectTabIndex) * 10
            }
            adapter?.clear()
            adapter?.addAll(subList)
        }
    }

    private fun showSuccess() {
        successDialog = SuccessDialog(this)
        XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(successDialog)
            .show()
    }

    override fun onTimeout() {

//        XPopup.Builder(this)
//            .dismissOnBackPressed(true)
//            .dismissOnTouchOutside(true)
//            .asCustom(screensaversDialog)
//            .show()
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        super.onBackPressed()
        val currentTime = System.currentTimeMillis()
        if (currentTime - touchTime >= waitTime) {
            ToastMgr.show("再按一次退出程序", "warn")
            touchTime = currentTime
        } else {
            AppManager.getAppManager().finishAllActivity()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(myServiceConnection)
        cameraUtils?.closeCamera()
    }

    private fun upDataVersion(apkUrl: String, version: String) {
        val manager: DownloadManager = DownloadManager.getInstance(this)
        manager.setApkName("lajifenlei$version.apk")
            .setDownloadPath(FileUtils.getSandboxCameraOutputPath(this))
            .setApkUrl(apkUrl)
            .setAuthorities("com.atjg.autocat")
            .setSmallIcon(R.mipmap.ic_launcher)
            .download()
        val updateConfiguration = UpdateConfiguration()
        updateConfiguration.isShowNotification = false
        updateConfiguration.isShowBgdToast = false
        updateConfiguration.setEnableLog(false)
        updateConfiguration.setJumpInstallPage(true)
        updateConfiguration.setForcedUpgrade(false)
        updateConfiguration.setOnDownloadListener(object : OnDownloadListener {
            override fun downloading(max: Int, progress: Int) {

            }

            override fun start() {

            }

            override fun done(apk: File?) {
                if (apk != null) {
                    installApk(apk)
                }
            }

            override fun cancel() {
            }

            override fun error(e: java.lang.Exception?) {
            }
        })
        manager.configuration = updateConfiguration
    }
    private fun installApk(tmpApk: File): Boolean {
        try {
            val intent = Intent()
            intent.setAction("android.intent.action.VIEW")
            if (Build.VERSION.SDK_INT >= 26) {
                val hasInstallPermission: Boolean = packageManager.canRequestPackageInstalls()
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity()
                    return false
                }
            }
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val contentUri = FileProvider.getUriForFile(
                    this,
                    "com.atjg.autocat",
                    tmpApk
                )
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(
                    Uri.fromFile(tmpApk),
                    "application/vnd.android.package-archive"
                )
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            startActivity(intent)
            return true
        } catch (e: Exception) {
            e.printStackTrace()
            printinfo("开始安装APP2:$e")
            return false
        }
    }
    private fun startInstallPermissionSettingActivity() {
        val intent = Intent()
        val packageURI = Uri.parse("package:$packageName")
        intent.setData(packageURI)
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction("android.settings.MANAGE_UNKNOWN_APP_SOURCES")
        } else {
            intent.setAction("android.settings.SECURITY_SETTINGS")
        }
        startActivity(intent)
    }
    @SuppressLint("SetTextI18n")
    private fun initSerial(){
       val shopStatus =  portUtils.addPort(shopPort)
        val clearStatus =   portUtils.addPort(cleanPort)
        portUtils.addDataListener(object : PortUtils.OnSerialPortListenr {
            @SuppressLint("SetTextI18n")
            override fun onDataReceived(com: String, data: String, commandFlag: String) {
              val status = if(data.length == 14){
                    val hexStr = data.toLowerCase(Locale.ROOT)
                    if(hexStr.contains("0ff6120100")){
                        "关闭 沐浴露进水"
                    }else if (data.contains("0ff6120300")){
                        "关闭 护毛素进水"
                    }else if (hexStr.contains("0ff6120400")){
                        "开 护毛素进水"
                    }else if (hexStr.contains("0ff6120200")){
                        "开 沐浴露进水"
                    }else if (hexStr.contains("0ff6120701")){
                        "关门"
                    }else{
                        ""
                    }
                }else{
                  if(commandFlag == "shopOut"){
                      "出货"
                  }else{
                      "查询"
                  }
                }
                portUtils.printData(this@MainActivity,"指令类型：$commandFlag 收到指令：$data $status")
                if(commandFlag == "shopOut"){
                    if(data.length == 20){
                       val subStr =  data.substring(12,14)
                        if (subStr == "01"){
                            successDialog?.setSuccess(true)
                        }else{
                            successDialog?.setSuccess(false)
                        }
                    }
                }else{
                    analyzeData(com,data.toLowerCase(Locale.ROOT),commandFlag)
                }


            }

            @SuppressLint("SetTextI18n")
            override fun onDataSend(data: String, commandFlag: String, isSend: Boolean) {
                Klog.d("-------发送指令：$data-----$isSend-")
              val status = when(commandFlag){
                  "fun-open","fun-open-door"->{
                      "开 门"
                  }
                  "fun-light-open"->{
                      "开 灯"
                  }
                  "fun-exhaust-open"->{
                      "开 排风-1"
                  }
                  "fun-clean-dj-open"->{
                      "开 清洗电机-1"
                  }
                  "fun-clean-dj-open-2"->{
                      "开 清洗电机-2"
                  }
                  "fun-clean-open-1" ->{
                      "开 清洗电磁阀-1"
                  }
                  "fun-clean-open-2" ->{
                      "开 清洗电磁阀-2"
                  }
                  "fun-clean-open-3"->{
                      "开 清洗电磁阀-3"
                  }
                  "fun-clean-open-4"->{
                      "开 清洗电磁阀-4"
                  }
                  "fun-clean-close-1"-> {
                      "关 清洗电磁阀-1"
                  }
                  "fun-clean-close-2"->{
                      "关 清洗电磁阀-2"
                  }
                  "fun-clean-close-3"->{
                      "关 清洗电磁阀-3"
                  }
                  "fun-clean-close-4"->{
                      "关 清洗电磁阀-4"
                  }
                  "fun-myl-open"->{
                      "开 沐浴露"
                  }
                  "fun-myl-close"->{
                      "关 沐浴露"
                  }
                  "fun-hms-open"->{
                      "开 护毛素"
                  }
                  "fun-hms-close"->{
                      "关 护毛素"
                  }
                  "fun-clean-dj-close"->{
                      "关 清洗电机-1"
                  }
                  "fun-clean-dj-close-2"->{
                      "关 清洗电机-2"
                  }
                  "fun-nfj-open"->{
                      "开 暖风机"
                  }
                  "fun-ejpf-open"->{
                      "开 二级吹风"
                  }
                  "fun-nfj-close"->{
                      "关 暖风机"
                  }
                  "fun-exhaust-close"->{
                      "关 排风-1"
                  }
                  "fun-ejpf-close"->{
                      "关 二级吹风"
                  }
                  "fun-xjd-open"->{
                      "开 消毒灯"
                  }
                  "fun-hpf-open"->{
                      "开 排风-2"
                  }
                  "fun-xjd-close"->{
                      "关 消毒灯"
                  }
                  "fun-hpf-close"->{
                      "关 排风-2"
                  }
                  "fun-light-close"->{
                      "关 灯"
                  }
                  "myl-queryStatus"->{
                      "查询 沐浴露"
                  }
                  "hms-queryStatus"->{
                      "查询 护毛素"
                  }
                  "myl-addMYL"->{
                      "开 沐浴露进水"
                  }
                  "myl-openMYLAdd"->{
                      "开 沐浴露电机加"
                  }
                  "myl-closeMYLAdd"->{
                      "关 沐浴露电机加"
                  }
                  "myl-closeMYL"->{
                      "关 沐浴露进水"
                  }
                  "hms-addHMS"->{
                      "开 护毛素进水"
                  }
                  "hms-openHMSAdd"->{
                      "开 护毛素电机加"
                  }
                  "hms-closeHMSAdd"->{
                      "关 护毛素电机加"
                  }
                  "hms-closeMYL"->{
                      "关 护毛素进水"
                  }
                  else->""
                }
                portUtils.printData(this@MainActivity,"发送指令：${data.lowercase(Locale.ROOT)} $status")
                if (commandFlag.startsWith("config")) {
                    val map = mutableMapOf<String, String>()
                    map["type"] = "sendHex"
                    map["hex"] = data
                    map["commandFlag"] = commandFlag
                    EventBus.getDefault().post(map)
                }

            }
        })
        queryStatus("myl-queryStatus")
    }
    private fun analyzeData(com: String,hexStr:String, commandFlag:String){
        if(hexStr.length == 14){
            if(hexStr.contains("0ff6120100")){
                App.mHanler?.postDelayed({
                    closeInsetWater()
                },500)
            }else if (hexStr.contains("0ff6120300")){
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"060600030000787d", "hms-closeMYL")
                    queryStatus = false
                },500)
            }
        }

        if (commandFlag.startsWith("myl")){
            mylHexResult(hexStr,commandFlag)
        }else if (commandFlag.startsWith("hms")){
            hmsHexResult(hexStr,commandFlag)
        }else if (commandFlag.startsWith("fun")){
            cleaning(hexStr,commandFlag)
        }
    }

    private fun queryStatus(commandFlag:String){
        queryStatus  = true
        portUtils.sendHex(cleanPort,"0ff61347ae",commandFlag)
    }
    //添加沐浴露
    private fun addMyl(){
        portUtils.sendHex(cleanPort,"060600010001187d","myl-addMYL")
        //沐浴露电机 加
        App.mHanler?.postDelayed({
            portUtils.sendHex(cleanPort,"06060005000159bc","myl-openMYLAdd")
        },600)
        val time7 = SPUtils.getInstance().getInt("time7")
        App.mHanler?.postDelayed({
            //倒计时沐浴露电机
            closeAddMyl()
        },1200 + time7 * 1000L)
    }
    private fun closeInsetWater(){
        portUtils.sendHex(cleanPort,"060600010000d9bd", "myl-closeMYL")
        App.mHanler?.postDelayed({
            queryStatus("hms-queryStatus")
        },600)
    }
    private fun mylHexResult(hexStr:String, commandFlag:String){
        when (commandFlag) {
            "myl-queryStatus"->{
                if(hexStr.length == 22) {
                    val mylStatusUp = hexStr.substring(6, 10)
                    if (mylStatusUp == "0000") {
                        //加入沐浴液
                        App.mHanler?.postDelayed({
                            addMyl()
                        },500)

                    }else{
                        val hmsStatusUp = hexStr.substring(10, 14)
                        if (hmsStatusUp == "0000") {
                           App.mHanler?.postDelayed({
                               portUtils.sendHex(cleanPort,"060600030001b9bd","hms-addHMS")
                           },500)
                            App.mHanler?.postDelayed({
                                //开启护毛素电机 加
                                openAddHms()
                            },1000)
                        }else{
                            queryStatus = false
                        }
                    }
                }else{
                    queryStatus = false
                }
            }
        }
    }
    private fun closeAddMyl(){
        //倒计时结束后关闭 06 06 00 05 00 00
        portUtils.sendHex(cleanPort,"060600050000987c","myl-closeMYLAdd")
    }
    private fun hmsHexResult(hexStr:String, commandFlag:String){
        when (commandFlag) {
            "hms-queryStatus"->{
                if(hexStr.length == 22) {
                    val hmsStatusUp = hexStr.substring(10, 14)
                    if (hmsStatusUp == "0000") {
                        portUtils.sendHex(cleanPort,"060600030001b9bd","hms-addHMS")
                        App.mHanler?.postDelayed({
                            //开启护毛素电机 加
                            openAddHms()
                        },600)
                    }else{
                        queryStatus = false
                    }
                }else{
                    queryStatus = false
                }
            }
        }
    }
    private fun openAddHms(){
        portUtils.sendHex(cleanPort,"060600060001a9bc","hms-openHMSAdd")
        App.mHanler?.postDelayed({
            val time8 = SPUtils.getInstance().getInt("time8")
            model.testTime(time8 * 1000L,{},{
                closeAddHms()
            })
        },600)
    }
    private fun closeAddHms(){
        //倒计时结束后关闭
        portUtils.sendHex(cleanPort,"060600060000687c","hms-closeHMSAdd")
    }
    private fun cleaning(hexStr:String, commandFlag:String){
        when(commandFlag){
            "fun-open"->{
                MusicPlayUtils.playBgM(this,R.raw.music_open_door)
                if(hexStr.contains("0ff6120701")){
                    binding.llWashIng.visibility = View.VISIBLE
                    binding.llTaoCan.visibility=View.INVISIBLE
                    initCamera()
                    App.mHanler?.postDelayed({
                        queryNetPhoto()
                    },3000)
                    //打开箱体照明灯 06 06 00 08 00 01
                    portUtils.sendHex(cleanPort,"060600080001c87f","fun-light-open")
                    //打开箱体后排风 06 06 00 0a 00 01
                    App.mHanler?.postDelayed({
                        portUtils.sendHex(cleanPort,"0606000a000169bf","fun-exhaust-open")
                    },500)
                    //打开清洗电机
                    App.mHanler?.postDelayed({
                        portUtils.sendHex(cleanPort,"050600020001e84e","fun-clean-dj-open")
                    },1000)
                    //打开清洗
                    App.mHanler?.postDelayed({
                        MusicPlayUtils.playBgM(this,R.raw.music_clean_start)
                        openClean("fun-clean-open-1")
                    },1500)
                }
            }
            "fun-open-door"->{
                queryNetPhoto()
                changeProgress(6)
                //关门
                if(hexStr.contains("0ff6120701")){
                    MusicPlayUtils.playBgM(this,R.raw.music_xd_start)
                    // 打开消毒灯 06 06 00 09 00 01
                    portUtils.sendHex(cleanPort,"06060009000199bf","fun-xjd-open")
                    //打开清洗电磁阀 06 06 00 07 00 01
                    App.mHanler?.postDelayed({
                        portUtils.sendHex(cleanPort,"060600070001f87c","fun-clean-open-4")
                    },500)
                    //打开清洗电机
                    App.mHanler?.postDelayed({
                        portUtils.sendHex(cleanPort,"050600020001e84e","fun-clean-dj-open-2")
                    },1000)
                    //打开箱体后排风 06 06 00 0a 00 01
                    App.mHanler?.postDelayed({
                        portUtils.sendHex(cleanPort,"0606000a000169bf","fun-hpf-open")
                    },1500)

                    App.mHanler?.postDelayed({
                        model.testTime(60000,{
                            stopTime = it
                            stopProgress = "fun-hpf-open"
                        },{
                            closeClean("fun-clean-close-4")
                        })
                    },2000)
                }
            }

        }
    }
    private fun openClean(commandFlag:String){
        //打开清洗电子阀 06 06 00 07 00 01
        portUtils.sendHex(cleanPort,"060600070001f87c",commandFlag)
        when (commandFlag) {
            "fun-clean-open-1" -> {
                changeProgress(0)
                //打开清洗
                App.mHanler?.postDelayed({
                    val time1 = SPUtils.getInstance(taocan).getInt("time1",60)
                    model.testTime(time1.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-clean-open-1"
                    },{
                        closeClean("fun-clean-close-1")
                    })
                },500)
            }
            "fun-clean-open-2" -> {
                changeProgress(2)
                App.mHanler?.postDelayed({
                    val time3 = SPUtils.getInstance(taocan).getInt("time3")
                    model.testTime(time3.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-clean-open-2"
                    },{
                        closeClean("fun-clean-close-2")
                    })
                },500)
            }
            "fun-clean-open-3" -> {
                changeProgress(4)
                App.mHanler?.postDelayed({
                    val time5 = SPUtils.getInstance(taocan).getInt("time5")
                    model.testTime(time5.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-clean-open-3"
                    },{
                        closeClean("fun-clean-close-3")
                    })
                },500)

            }
        }
    }
    private fun closeClean(commandFlag:String){
        //关闭清洗电子阀 06 06 00 07 00 00
        portUtils.sendHex(cleanPort,"06060007000039bc",commandFlag)
        when (commandFlag) {
            "fun-clean-close-1" -> {
                changeProgress(1)
                //打开沐浴露出水电磁阀 06 06 00 02 00 01
                App.mHanler?.postDelayed({
                    MusicPlayUtils.playBgM(this,R.raw.music_myl_start)
                    portUtils.sendHex(cleanPort,"060600020001e87d","fun-myl-open")
                },500)
                //打开沐浴露出水电磁阀 06 06 00 02 00 01
                App.mHanler?.postDelayed({
                    val time2 = SPUtils.getInstance(taocan).getInt("time2")
                    model.testTime(time2.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-myl-open"
                    },{
                        closeMyl("fun-myl-close")
                    })
                },1000)
            }
            "fun-clean-close-2" -> {
                changeProgress(3)
                //打开护毛素出水电磁阀
                App.mHanler?.postDelayed({
                    MusicPlayUtils.playBgM(this,R.raw.music_hms_start)
                    portUtils.sendHex(cleanPort,"060600040001087c","fun-hms-open")
                },500)
                App.mHanler?.postDelayed({
                    val time4 = SPUtils.getInstance(taocan).getInt("time4")
                    model.testTime(time4.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-hms-open"
                    },{
                        closeHms("fun-hms-close")
                    })
                },500)
            }
            "fun-clean-close-3" -> {
                changeProgress(5)
                //关闭清洗电机 05 06 00 02 00 00
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"050600020000298e","fun-clean-dj-close")
                },500)
                //打开暖风机 05 06 00 01 00 01
                App.mHanler?.postDelayed({
                    MusicPlayUtils.playBgM(this,R.raw.music_hf_start)
                    portUtils.sendHex(cleanPort,"050600010001184e","fun-nfj-open")
                },1000)
                // 打开二级吹风 06 06 00 0b 00 01
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"0606000b0001387f","fun-ejpf-open")
                },1500)
                //关闭暖风机 05 06 00 01 00 01
                App.mHanler?.postDelayed({
                    val time6 = SPUtils.getInstance(taocan).getInt("time6")
                    model.testTime(time6.toLong()*1000,{
                        stopTime = it
                        stopProgress = "fun-ejpf-open"
                    },{
                        MusicPlayUtils.playBgM(this,R.raw.music_hg_stop)
                        closeNfj("fun-nfj-close")
                    })
                },2000)
            }
            "fun-clean-close-4" -> {
                MusicPlayUtils.playBgM(this,R.raw.music_xd_stop)
                // 关闭消毒灯 06 06 00 09 00 00
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"060600090000587f","fun-xjd-close")
                },500)
                //关闭清洗电机
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"050600020000298e","fun-clean-dj-close-2")
                },1000)
                //关闭箱体后排风 06 06 00 0a 00 00
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"0606000a0000a87f","fun-hpf-close")
                },1500)
                //关闭照明
                App.mHanler?.postDelayed({
                    portUtils.sendHex(cleanPort,"06060008000009bf","fun-light-close")
                },2000)
                App.mHanler?.postDelayed({
                    binding.llWashIng.visibility = View.GONE
                    binding.llTaoCan.visibility=View.VISIBLE
                    cameraUtils?.closeCamera()
                    queryStatus("myl-queryStatus")
                    changeProgress(-1)
                },2000)
            }
        }
    }
    private fun closeNfj(commandFlag:String){
        //关闭暖风机 05 06 00 01 00 01
        portUtils.sendHex(cleanPort,"050600010000d98e",commandFlag)
        //关闭关闭箱体后排风
        App.mHanler?.postDelayed({
            portUtils.sendHex(cleanPort,"0606000a0000a87f","fun-exhaust-close")
        },500)
        // 关闭二级吹风 06 06 00 0b 00 01
        App.mHanler?.postDelayed({
            portUtils.sendHex(cleanPort,"0606000b0000f9bf","fun-ejpf-close")
        },1000)
        // 开门 0f 06 00 16 00 01
         App.mHanler?.postDelayed({
             MusicPlayUtils.playBgM(this,R.raw.music_close_door)
             portUtils.sendHex(cleanPort,"0f0600160001a8e0","fun-open-door")
         },1500)
    }
    private fun closeMyl(commandFlag:String){
        //关闭沐浴露电子阀 06 06 00 02 00 00
        portUtils.sendHex(cleanPort,"06060002000029bd",commandFlag)
        App.mHanler?.postDelayed({
            openClean("fun-clean-open-2")
        },500)
    }
    private fun closeHms(commandFlag:String){
        portUtils.sendHex(cleanPort,"060600040000c9bc",commandFlag)
        App.mHanler?.postDelayed({
            openClean("fun-clean-open-3")
        },500)
    }
    private fun initCamera() {
        cameraUtils = CameraUtils(
            this,
            "0",
            binding.tvTextureView,
            "$externalCacheDir"
        ) { path ->
            runOnUiThread {
                model.uploadImg(orderNo,File(path))
            }
        }
        cameraUtils?.reopenCamera()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun changeProgress(progress:Int){
        this.progress = progress
        progressAdapter.notifyDataSetChanged()
        if (progress == -1){
            queryNetPhoto()
        }else{
            usbTakPhoto()
        }
    }
    @SuppressLint("AuthLeak")
    private fun queryNetPhoto() {
        val url = "http://192.168.1.10/webcapture.jpg?command=snap&channel=0"
        model.queryBitmap(this, url)
    }
    //usb拍照
    private fun usbTakPhoto() {
        cameraUtils?.capture("usbImage.jpg")

    }
}
@OptIn(ExperimentalStdlibApi::class)
fun main() {
    val array = byteArrayOf(
        0x06,
        0x06.toByte(),
        0x00,
        0x04,
        0x00,
        0x01
    ).crc16().toHexString()
    println(array)
}
